package cn.fl.extcon.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.project.vo.*;
import net.sf.json.JSONArray;

import org.apache.velocity.VelocityContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.base.framework.utils.VelocityUtil;
import cn.fl.capital.condition.CapPayInfoQueryCondition;
import cn.fl.capital.condition.CapPayeeInfoQueryCondition;
import cn.fl.capital.service.ICapPayInfoService;
import cn.fl.capital.service.ICapPayeeInfoService;
import cn.fl.capital.vo.CapPayInfoVO;
import cn.fl.capital.vo.CapPayeeInfoVO;
import cn.fl.customer.controller.CstNpSocialRlController;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.service.ICstNpSocialRlService;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.extcon.condition.SysExpTmplQueryCondition;
import cn.fl.extcon.constant.ExtconConstant;
import cn.fl.extcon.constant.SysExpTmplConstant;
import cn.fl.extcon.service.ISysExpTmplService;
import cn.fl.extcon.vo.SysExpTmplVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.ProjectUtils;
import cn.fl.project.condition.PrjCstBscInfoQueryCondition;
import cn.fl.project.condition.PrjPrdBscInfoQueryCondition;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.condition.PrjPrdPaySchDQueryCondition;
import cn.fl.project.condition.PrjQuatPrpsFeeQueryCondition;
import cn.fl.project.condition.PrjQuatPrpsQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjCstBscInfoConstant;
import cn.fl.project.constant.PrjPrdBscInfoConstant;
import cn.fl.project.constant.PrjPrdPaySchDConstant;
import cn.fl.project.constant.PrjQuatPrpsConstant;
import cn.fl.project.dto.PrjCstBscInfoDTO;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjCstBscInfoService;
import cn.fl.project.service.IPrjPrdBscInfoService;
import cn.fl.project.service.IPrjPrdDtlCarService;
import cn.fl.project.service.IPrjPrdDtlService;
import cn.fl.project.service.IPrjPrdPaySchDService;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.service.IPrjPrdVehInfoService;
import cn.fl.project.service.IPrjQuatPrpsFeeService;
import cn.fl.project.service.IPrjQuatPrpsService;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysRegionService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import fl.customer.facade.customer.api.ICustomerApiService;
import fl.customer.facade.customer.api.ICustomerQueryApiService;
import fl.customer.facade.customer.condition.CstNpBscInfoQueryCondition;
import fl.customer.facade.customer.condition.CstNpSocialRlQueryCondition;
import fl.customer.facade.customer.dto.CstNpBscInfoDTO;
import fl.customer.facade.customer.dto.CstNpSocialRlDTO;
import fl.spl.facade.spl.api.ISplInfoApiService;
import fl.spl.facade.spl.dto.SplBankDTO;

/**
 * @Description: 导出模板表 控制层
 */
@Controller
@RequestMapping("/extcon/sysExpTmpl")
public class SysExpTmplController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(SysExpTmplController.class);
	
	/**
	 * PrjBscInfo 项目基础信息服务
	 */
	@Autowired
	private IPrjBscInfoService prjBscInfoService;
	/**
	 * CstBscInfo 客户基础信息服务prjQuatPrpsService
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	
	@Autowired
	private IPrjQuatPrpsService prjQuatPrpsService;
	
	@Autowired
	private IPrjQuatPrpsFeeService prjQuatPrpsFeeService;
	
	@Autowired
	private ISysRegionService sysRegionService;
	
	@Autowired
	private IPrjCstBscInfoService prjCstBscInfoService;
	
	@Autowired
	private ICstNpSocialRlService cstNpSocialRlService;
	
	/**
	 * 客户模块基础信息服务
	 */
	@Autowired
	private ICustomerApiService customerApiService;
	@Autowired
	private ICustomerQueryApiService customerQueryApiService;

	
	/**
	 * PrjPrdBscInfo 项目产品基础信息服务
	 */
	@Autowired
	private IPrjPrdBscInfoService prjPrdBscInfoService;
	
	@Autowired
	private IPrjPrdDtlService prjPrdDtlService;
	
	@Autowired
	private IPrjPrdVehInfoService prjPrdVehInfoService;
	
	@Autowired
	private IPrjPrdPaySchMService prjPrdPaySchMService;
	
	@Autowired
	private IPrjPrdPaySchDService prjPrdPaySchDService;
	@Autowired
	private IPrjPrdDtlCarService prjPrdDtlCarService;
	/**
	 * 供应商服务
	 */
	@Autowired
	private ISplInfoApiService splInfoApiService;
	@Autowired
	private ICapPayInfoService capPayInfoService;
	@Autowired
	private ICapPayeeInfoService capPayeeInfoService;
	
	
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	/**
	 * SysExpTmpl 服务层BEAN
	 */
	@Autowired
	private ISysExpTmplService sysExpTmplService;
    
	/**
	 * 跳转模板下载合同页面
	 */
	@RequestMapping(value = "/toExtConPage.do", method = { RequestMethod.GET})
	
	public ModelAndView toExtConPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toExtConPage", "加载SysExpTmpl模板下载合同页面.",CurrentThreadContext.getCurrentUserName());
		//查询 项目所属事业部
		String prjId =  request.getParameter("prjId");
		ModelAndView mav = new ModelAndView("project/prjcont/prjExtCon");
		mav.addObject("prjId", prjId);
		return mav;
	}
	
	/**
	 * 初始化列表
	 */

	@RequestMapping(value = "/initSysExpTmplList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initSysExpTmplList(HttpServletRequest request, HttpServletResponse response) {
		SysExpTmplQueryCondition qc = new SysExpTmplQueryCondition();
		BaseLogUtils.info(logger, "initSysExpTmplList", "初始化SysExpTmpl列表页面数据.DATA:"+JSONObject.toJSONString(qc), 
				CurrentThreadContext.getCurrentUserName());
		PrjBscInfoVO prjBscInfoVO = null;
		String buOrgCd = null;
		List<SysExpTmplVO> list =null;
		String prjId = request.getParameter("prjId");
		if(StringUtils.isNotEmpty(prjId)){
			prjBscInfoVO = prjBscInfoService.selectById(Long.parseLong(prjId));
			if(prjBscInfoVO != null){
				buOrgCd = prjBscInfoVO.getBuOrgCd();
			}
		}
		if (StringUtils.isNotEmpty(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			if(StringUtils.isNotEmpty(prjBscInfoVO.getPrjTypCd())
					&& PrjBscInfoConstant.PRJ_TYP_CD_GHKD.equals(prjBscInfoVO.getPrjTypCd())){
				qc.setGrpCd(SysExpTmplConstant.CODE_GRP_CD_002);
			}else{
				qc.setGrpCd(SysExpTmplConstant.CODE_GRP_CD_001);
			}
		    list = this.sysExpTmplService.searchList(qc);
		}
		if (CollectionUtils.isNotEmpty(list)) {
    		return new ListPageVO<SysExpTmplVO>(list, list.size());
    	}
    	return new ListPageVO<SysExpTmplVO>(new ArrayList<SysExpTmplVO>(), 0);
    }
	/**
	 * 下载合同模板
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/toCreateDoc.do", method = { RequestMethod.GET})
	@ResponseBody
	  public void toCreateDoc(HttpServletRequest request, HttpServletResponse response) {
		
		String sysCd = CurrentThreadContext.getCurrentSysCd();
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
			Long prjId = Long.parseLong(request.getParameter("prjId"));//项目id
	    	String expTmplPath = request.getParameter("expTmplPath");//导出模板路径
	    	String tmplFileNm = request.getParameter("tmplFileNm");//模板文件名称
	    	String tmplNm = request.getParameter("tmplNm");//模板名称：导出文件名
	    	String fileTypCd = request.getParameter("fileTypCd");//导出文件类型
	    	String isOnlyTemp = request.getParameter("isOnlyTemp");//是否直接输出模板
	    	String grpCd = request.getParameter("grpCd");//模板组代码
	    	VelocityContext vc = new VelocityContext();
	    	//生成文件类型  1 pdf 2 doc 3 xls
	    	//判断是否直接输出模板 //0否 1是
	    	if(Integer.parseInt(isOnlyTemp) == BaseConstant.IS_YESNO_NO){
	    		try {
	    			PrjBscInfoVO prjBscInfoVO = null;
	    			if(StringUtils.isNotEmpty(prjId)){
	    				prjBscInfoVO = prjBscInfoService.selectById(prjId);
	    			}
	    			//根据项目id 查询 项目方案 计算合同首期款（全部）kangcheng start
	    			PrjQuatPrpsQueryCondition prjQuatQC = new PrjQuatPrpsQueryCondition();
	    			prjQuatQC.setPrjId(Long.valueOf(prjId));
	    			prjQuatQC.setIsFormalPrps(BaseConstant.IS_YESNO_YES);
	    			List<PrjQuatPrpsVO> quatList = this.prjQuatPrpsService.searchList(prjQuatQC);
	    			Double total = 0d;
	    			if(CollectionUtils.isNotEmpty(quatList)){
	    				PrjQuatPrpsVO prpsDTO = quatList.get(0);
	    				//租赁物总价值
	    				if(null==prpsDTO.getTotLsItmAmt()){
	    					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_602,"生成合同校验-租赁物总价值为空！");
	    				}
	    				//String contAmt =ProjectUtils.hangeToBig(prpsDTO.getTotLsItmAmt()==null?0:DecimalUtils.convertFenToYuan(prpsDTO.getTotLsItmAmt().longValue()));
//	    				map.put("4",contAmt );//租赁物总价值
//	    				map.put("5", DecimalUtils.convertFenToYuan(prpsDTO.getTotLsItmAmt().longValue()).toString());//租赁物总价值
	    				 PrjQuatPrpsFeeQueryCondition feeQc  = new PrjQuatPrpsFeeQueryCondition();
	    				 feeQc.setPrpsId(prpsDTO.getId());
	    				 List<PrjQuatPrpsFeeVO> feeList = this.prjQuatPrpsFeeService.searchList(feeQc);
	    				 
	    				 double firstTotalAmt = 0;
	    				 if(CollectionUtils.isNotEmpty(feeList)){
	    					 for (PrjQuatPrpsFeeVO prjQuatPrpsFeeVO : feeList) {
	    						 if(prjQuatPrpsFeeVO.getFeeTypCd().equals(PrjQuatPrpsConstant.CODE_FEE_WAY_TYPE_DOWNPAY) && StringUtils.isNotBlank(prjQuatPrpsFeeVO.getFeeAmt()+"")){
	    							 //工行项目首期款
	    							 vc.put("firstAmt_G", DecimalUtils.convertFenToYuan(prjQuatPrpsFeeVO.getFeeAmt().longValue()));
	    							 vc.put("firstAmt_GU", ProjectUtils.hangeToBig(DecimalUtils.convertFenToYuan(prjQuatPrpsFeeVO.getFeeAmt().longValue())));
	    						 }
	    						if(prjQuatPrpsFeeVO.getCntWayCd().equals(PrjQuatPrpsConstant.CODE_PRJ_QUAT_CNT_WAY_DOWNPAY)){
	    							total = DecimalUtils.add(total, prjQuatPrpsFeeVO.getFeeAmt());
	    							firstTotalAmt =  DecimalUtils.add(firstTotalAmt, prjQuatPrpsFeeVO.getFeeAmt());
	    						}
	    					}
	    					 total = DecimalUtils.convertFenToYuan(total.longValue());
	    					 String totalAmt = ProjectUtils.hangeToBig(total);
	    					 vc.put("firstFeeL", total);//首期
			    			 vc.put("firstFeeU", totalAmt);//首期:大写
	    						
	    				 }
	    				 if(null==prpsDTO.getActLsAmt()){
	    						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_602,"生成合同校验-实际融资价值为空！");
	    					}
	    				 double  shouldAmt = DecimalUtils.sub(DecimalUtils.convertYuanToFen(prpsDTO.getContAmt()), firstTotalAmt);
	    				//  map.put("8",prpsDTO.getContAmt()-total);
	    				 String shouldAmtStr = ProjectUtils.hangeToBig(DecimalUtils.convertFenToYuan(Double.valueOf(shouldAmt).longValue()));
	    					vc.put("actLsAmtL", Double.valueOf(DecimalUtils.convertFenToYuan(Double.valueOf(shouldAmt).longValue())).toString());//融资额
		    				vc.put("actLsAmtU", shouldAmtStr);//融资额：大写
	    			}
	    			//根据项目id 查询 项目方案 计算合同首期款（全部）kangcheng end
	    			//查询区域
	    			String area ="";
	    			if(prjBscInfoVO != null && StringUtils.isNotBlank(prjBscInfoVO.getRgnPrCd())){
	    				List<KeyValueVO> provinceKVList = this.sysRegionService.searchProvinceKVList();
	    				if(CollectionUtils.isNotEmpty(provinceKVList)){
	    					String provinceV = "";
	    					for(int i =0 ; i < provinceKVList.size() ; i++){
	    						if(prjBscInfoVO.getRgnPrCd().equals(provinceKVList.get(i).getKey())){
	    							provinceV = provinceKVList.get(i).getValue();
	    							area += provinceV;
	    							break;
	    						}
	    					}
	    					
	    					List<KeyValueVO> cityKVList = this.sysRegionService.searchRegineKVList(prjBscInfoVO.getRgnPrCd());
	    					if(StringUtils.isNotBlank(prjBscInfoVO.getRgnCyCd()) && CollectionUtils.isNotEmpty(cityKVList)){
	    						String cityV = "";
	    						for(int i =0 ; i < cityKVList.size() ; i++){
		    						if(prjBscInfoVO.getRgnCyCd().equals(cityKVList.get(i).getKey())){
		    							cityV = cityKVList.get(i).getValue();
		    							area += cityV;
		    							break;
		    						}
		    					}
	    					}
	    				}
	    			}
	    			vc.put("area",area);
	    			//查询客户信息，项目，合格证相关信息等放入vc   
	    			//合同信息
	    			vc.put("lsCntNo",prjBscInfoVO.getLsCntNo());//合同号
	    			vc.put("cstNm",prjBscInfoVO.getCstNm());//承租人名称
	    			//授权书   ：身份证号CERT_NO
	    			logger.info("客户id======="+prjBscInfoVO.getCstId()+"========");
	    			CstBscInfoVO cstBscInfoVo = cstBscInfoService.selectById(prjBscInfoVO.getCstId());
	    			vc.put("certNo",cstBscInfoVo.getCertNo());//身份证号
	    			CstNpBscInfoQueryCondition cnbiQc = new CstNpBscInfoQueryCondition();
	    			List<Long> idList = new ArrayList<>();
	    			idList.add(prjBscInfoVO.getCstId());
	    			cnbiQc.setIdList(idList);
	    			List<CstNpBscInfoDTO> cnbiList = customerQueryApiService.searchCstNpBscInfoList(cnbiQc);
	    			if(CollectionUtils.isNotEmpty(cnbiList)){
	    				vc.put("postAddr",cnbiList.get(0).getPostAddr());//邮寄地址=通讯地址
	    				vc.put("mp1",cnbiList.get(0).getMp1());//手机号1
	    				vc.put("workPlc", cnbiList.get(0).getWorkPlc());//单位
	    				vc.put("workAddr", cnbiList.get(0).getWorkAddr());//单位地址
	    				vc.put("workTel", cnbiList.get(0).getWorkTel());//单位电话
	    			}
	    			
	    			PrjPrdBscInfoQueryCondition qc = new PrjPrdBscInfoQueryCondition();
	    			qc.setPrjId(prjId);
	    			List<PrjPrdBscInfoVO> prjList = prjPrdBscInfoService.searchList(qc);
	    			if(CollectionUtils.isNotEmpty(prjList)){
		    			for (int i = 0; i < prjList.size(); i++) {
		    				vc.put("splNm", prjList.get(i).getSplNm());//供应商名称
		    				vc.put("mfrNm", prjList.get(i).getMfrNm());//厂商名称
		    				vc.put("prdTypCdNm", prjList.get(i).getPrdTypCdNm());//产品类别
						}
	    			}
	    			if(CollectionUtils.isNotEmpty(prjList)){
	    				SplBankDTO splBank = this.splInfoApiService.selectPrdSplBankById(prjList.get(0).getSplAccNoId());
		    			CapPayInfoQueryCondition payInfoQueryCondition=new CapPayInfoQueryCondition();
		    			payInfoQueryCondition.setPrjId(prjId);
		    			List<CapPayInfoVO> capPayList = this.capPayInfoService.searchList(payInfoQueryCondition);
		    			if(CollectionUtils.isNotEmpty(capPayList)){
		    				Long payId = capPayList.get(0).getId();
		    				CapPayeeInfoQueryCondition payeeInfoQueryCondition = new CapPayeeInfoQueryCondition();
		    				payeeInfoQueryCondition.setPayId(payId);
		    				payeeInfoQueryCondition.setPurpCd(PrjPrdBscInfoConstant.SPL_BANK_NO_TP);
		    				List<CapPayeeInfoVO> payeeList= this.capPayeeInfoService.searchList(payeeInfoQueryCondition);
		    				if(CollectionUtils.isNotEmpty(payeeList)){
		    					vc.put("rcptUnt",payeeList.get(0).getRcptUnt());//账号名称
		    					vc.put("payeeBkNm",payeeList.get(0).getPayeeBkNm());//开户行
		    					vc.put("accNo",payeeList.get(0).getAccNo());//账号
		    				}
		    			}
		    			//放款信息里面没有查到查询项目上的账号信息
		    			if(!vc.containsKey("rcptUnt")){
		    				 if(null!=splBank){
		    					vc.put("rcptUnt",splBank.getRcptUnt());//账号名称
		    					vc.put("payeeBkNm",splBank.getBkNm());//开户行
		    					vc.put("accNo",splBank.getAccNo());//账号
		    				 }
		    			}
	    			}
	    			PrjPrdDtlQueryCondition pdQc = new PrjPrdDtlQueryCondition();
    				pdQc.setPrjId(prjId);
    				List<PrjPrdDtlVO> pdlist = prjPrdDtlService.selectList(pdQc);
    				if(CollectionUtils.isNotEmpty(pdlist)){
    					//车辆id去查=>品牌，系列，款式，型号，车身颜色，车架号
    					vc.put("prdNm", pdlist.get(0).getPrdNm());//品牌
	    				vc.put("prdMdl", pdlist.get(0).getPrdMdl());//型号
	    				vc.put("vin", pdlist.get(0).getVin());//车架号
	    				vc.put("paySchNo", pdlist.get(0).getPaySchNo());//支付表号
	    				vc.put("engNo", pdlist.get(0).getEngNo());//发动机号 20170706  //2017/9/20 :zhanggtongtong
	    				
	    				logger.info("=======产品明细id========="+pdlist.get(0).getPrdDtlId()+"=================");
	    				if(StringUtils.isNotEmpty(pdlist.get(0).getPrdDtlId())){
	    					PrjPrdDtlCarVO ppdcVo =  prjPrdDtlCarService.selectById(pdlist.get(0).getPrdDtlId());
	    					if(ppdcVo != null){
		    				vc.put("carCl", ppdcVo.getCarCl());//车身颜色
		    				//vc.put("engNo", ppdcVo.getEngMdl());//发动机号  //2017/9/20 :zhanggtongtong
	    					}
	    				}
	    				logger.info("=======车辆id   ========="+pdlist.get(0).getActPrdId()+"=================");
	    				if(StringUtils.isNotEmpty(pdlist.get(0).getActPrdId())){
	    					PrjPrdVehInfoVO ppVo = prjPrdVehInfoService.selectById(pdlist.get(0).getActPrdId());
	    					if(ppVo != null){
			    				vc.put("carCl", ppVo.getCarCl());//车身颜色
			    				//vc.put("engNo", ppVo.getEngNo());//发动机号  //2017/9/20 :zhanggtongtong
	    					}
	    				}
	    				
    					//支付表id
	    				if(StringUtils.isNotEmpty(pdlist.get(0).getPaySchId())){
	    					PrjPrdPaySchMVO pppsm = prjPrdPaySchMService.selectById(pdlist.get(0).getPaySchId());
		    				vc.put("contAmtL", pppsm.getContAmt()/100);//合同金额
		    				vc.put("contAmtU", ProjectUtils.hangeToBig(pppsm.getContAmt()/100));//合同金额 :大写
//		    				vc.put("actLsAmtL", pppsm.getActLsAmt()/100);//融资额
//		    				vc.put("actLsAmtU", ProjectUtils.hangeToBig(pppsm.getActLsAmt()/100));//融资额：大写
		    				
		    				vc.put("lsPd", pppsm.getLsPd());//租赁期数
		    					    				
		    				List<KeyValueVO> payList = sysDictionaryApiService.getKvList(ExtconConstant.PYA_WAY_CD,sysCd,orgCd);
		    				if(CollectionUtils.isNotEmpty(payList)){
			    				for (KeyValueVO keyValueVO : payList) {
									if(pppsm.getPayWayCd().equals(keyValueVO.getKey()))
										vc.put("payWayCd", keyValueVO.getValue());
								}
		    				}
		    				PrjPrdPaySchDQueryCondition ppdqc = new PrjPrdPaySchDQueryCondition();
		    				ppdqc.setPaySchId(pdlist.get(0).getPaySchId());
		    				ppdqc.setPayPd(1L);//求第一期
		    				ppdqc.setFeeTypCd(ExtconConstant.FEE_TYP_CD_R);//费用类型：租金
		    				List<PrjPrdPaySchDVO> ppdList = prjPrdPaySchDService.searchList(ppdqc);
		    				Double feeAmt = 0D;
		    				if(CollectionUtils.isNotEmpty(ppdList)){
		    					feeAmt = ppdList.get(0).getFeeAmt()/100; 
		    				}
		    				vc.put("feeAmt", DecimalUtils.cut(feeAmt,2));//每期租金金额
		    				vc.put("feeAmtU", ProjectUtils.hangeToBig(feeAmt));
		    				PrjPrdPaySchDQueryCondition ppdqc1 = new PrjPrdPaySchDQueryCondition();
		    				ppdqc1.setPaySchId(pdlist.get(0).getPaySchId());
		    				ppdqc1.setFeeTypCd(ExtconConstant.FEE_TYP_CD_F);
		    				List<PrjPrdPaySchDVO> fList = prjPrdPaySchDService.searchList(ppdqc1);
		    				Double firstFee = 0D;
		    				if(CollectionUtils.isNotEmpty(fList)){
		    					firstFee =	fList.get(0).getFeeAmt()/100;
		    				}
		    				//zhaoyong 增加尾付款查询
		    				ppdqc1.setFeeTypCd(ExtconConstant.FEE_TYP_CD_F_P);
		    				List<PrjPrdPaySchDVO> finalPayList = prjPrdPaySchDService.searchList(ppdqc1);
		    				Double finalPayFee = 0D;
		    				if(CollectionUtils.isNotEmpty(finalPayList)){
		    					finalPayFee =	finalPayList.get(0).getFeeAmt()/100;
		    				}
		    				vc.put("finalPayFee", finalPayFee);//尾付款
		    				vc.put("finalPayFeeU", ProjectUtils.hangeToBig(finalPayFee));
		    				
//		    				vc.put("firstFeeL", firstFee);//首期
//		    				vc.put("firstFeeU", ProjectUtils.hangeToBig(firstFee));//首期:大写
		    				vc.put("firstFee", firstFee);//首期租金
		    				
		    				ppdqc1.setFeeTypCd(ExtconConstant.FEE_TYP_CD_C_1);//咨询费1
		    				List<PrjPrdPaySchDVO> fList1 = prjPrdPaySchDService.searchList(ppdqc1);
		    				
		    			    Double fee1 = 0D;
		    			    if(CollectionUtils.isNotEmpty(fList1)){
		    					fee1 = fList1.get(0).getFeeAmt()/100;
		    				}	
		    			    ppdqc1.setFeeTypCd(ExtconConstant.FEE_TYP_CD_C_2);//咨询费2
		    			    List<PrjPrdPaySchDVO> fList2 = prjPrdPaySchDService.searchList(ppdqc1);
		    				
		    			    Double fee2 = 0D;
		    			    if(CollectionUtils.isNotEmpty(fList2)){
		    					fee2 = fList2.get(0).getFeeAmt()/100;
		    				}	

		    				vc.put("firstConsultFee", firstFee+fee1+fee2);//首期+咨询费
		    				vc.put("consultFee", fee1+fee2);//咨询费
		    				vc.put("consultFeeU", ProjectUtils.hangeToBig(fee1+fee2));//咨询费:大写
		    				ppdqc1.setFeeTypCd(ExtconConstant.FEE_TYP_CD_I);//保证金
		    				List<PrjPrdPaySchDVO> insuFeeList = prjPrdPaySchDService.searchList(ppdqc1);
		    				
		    			    Double insuFee = 0D;
		    			    if(CollectionUtils.isNotEmpty(insuFeeList)){
		    			    	insuFee = insuFeeList.get(0).getFeeAmt()/100;
		    				}	
		    				vc.put("insuFee", insuFee);//保证金
		    				vc.put("insuFeeU", ProjectUtils.hangeToBig(insuFee));//保证金:大写
		    				if(StringUtils.isNotEmpty(grpCd) && SysExpTmplConstant.CODE_GRP_CD_002.equals(grpCd)){
			    				//工行合同实际融资额
			    				Double actLsAmt = DecimalUtils.convertFenToYuan(pppsm.getActLsAmt().longValue());
			    				vc.put("actLsAmtL", actLsAmt);
			    				vc.put("actLsAmtU", ProjectUtils.hangeToBig(actLsAmt));//实际融资价值大写
			    				//服务费  咨询费1-经销商返利
			    				ppdqc1.setFeeTypCd(ExtconConstant.FEE_TYP_CD_C_8);//供应商返利
			    				List<PrjPrdPaySchDVO> fList8 = prjPrdPaySchDService.searchList(ppdqc1);
			    				Double fee8 = 0D;
			    				if(CollectionUtils.isNotEmpty(fList8)){
			    					fee8 = fList8.get(0).getFeeAmt()/100;
			    				}
			    				vc.put("serFee", DecimalUtils.sub(fee1, fee8));//服务费
			    				ppdqc.setPayPd(2l);
			    				List<PrjPrdPaySchDVO> ppdList2 = prjPrdPaySchDService.searchList(ppdqc);
			    				Double feeAmt2 = 0D;
			    				if(CollectionUtils.isNotEmpty(ppdList2)){
			    					feeAmt2 = ppdList2.get(0).getFeeAmt()/100; 
			    				}
			    				vc.put("feeAmt2", feeAmt2);//每期租金金额(工行取第二期)
			    				Double monthPay = DecimalUtils.add(DecimalUtils.mul(feeAmt2, 2),100);
			    				vc.put("monthPay", monthPay);
			    				//分期手续费
			    				vc.put("annIntRate", pppsm.getAnnIntRatePct());//分期费率
			    				vc.put("annInt", DecimalUtils.div(DecimalUtils.mul(actLsAmt , pppsm.getAnnIntRatePct()),100, 2));//分期费
			    				//年
			    				vc.put("year", (int)DecimalUtils.div(pppsm.getLsPd(), 12, 0));
			    				
		    				}
	    				}
    				}
    				//工行合同信息
    				if(StringUtils.isNotEmpty(grpCd) && SysExpTmplConstant.CODE_GRP_CD_002.equals(grpCd)){
    					//查询商品信息
    	    			PrjPrdBscInfoVO prdBscInfoVO = this.prjPrdBscInfoService.selectPrjPrdBscAndDetailInfoById(prjList.get(0).getId()+"");
    	    			if(null != prdBscInfoVO){
    	    				vc.put("brCdNm", prdBscInfoVO.getBrCdNm());//品牌
    	    				//vc.put("prdMdl", prdBscInfoVO.getPrjPrdCarInfoVO().getCarMdl());//车型
    	    				PrjPrdExtVO prjPrdCarInfoVO= prdBscInfoVO.getPrjPrdExtVO();
    	    				if(null != prjPrdCarInfoVO){
    	    					vc.put("carCl",prjPrdCarInfoVO.getCarCl());//颜色
    	    					vc.put("prdMdl", prjPrdCarInfoVO.getCarMdl());//车型
    	    				}
    	    				//产品价格
    	    				if(StringUtils.isNotEmpty(prdBscInfoVO.getPrdAmt()+"")){
    	    					vc.put("prdAmtL", prdBscInfoVO.getPrdAmt());
    		    				vc.put("prdAmtU", ProjectUtils.hangeToBig(prdBscInfoVO.getPrdAmt()));//产品价格大写
    		    				//剩余购车款  车辆总价 减 申请分期金额
    		    				vc.put("surPrdAmtL", DecimalUtils.sub(prdBscInfoVO.getPrdAmt(), total));
    		    				vc.put("surPrdAmtU", ProjectUtils.hangeToBig(DecimalUtils.sub(prdBscInfoVO.getPrdAmt(), total)));
    	    				}
    	    				
    	    				
    	    			}
    	    			//查询担保人信息
    	    			PrjCstBscInfoQueryCondition prjCstBscInfoQc = new PrjCstBscInfoQueryCondition();
    	    			prjCstBscInfoQc.setPrjId(prjId);
    	    			prjCstBscInfoQc.setCstRlTyp(PrjCstBscInfoConstant.CST_Rl_ATTR_GUARANTOR);
    	    			List<PrjCstBscInfoVO> prjCstBscInfoVOList =this.prjCstBscInfoService.searchList(prjCstBscInfoQc);
    	    			if(CollectionUtils.isNotEmpty(prjCstBscInfoVOList)){
    	    				vc.put("guarNm", prjCstBscInfoVOList.get(0).getCstNm());
    	    				vc.put("guarCertNo",prjCstBscInfoVOList.get(0).getCertNo());
    	    			}
    	    			//查询配偶信息
    	    			CstNpSocialRlQueryCondition cstNpSocQc= new CstNpSocialRlQueryCondition();
    	    			List<Long> cstIds= new ArrayList<Long>();
    	    			cstIds.add(prjBscInfoVO.getCstId());
    	    			cstNpSocQc.setCstIdList(cstIds);
    	    			cstNpSocQc.setRlTypCd(ExtconConstant.RL_TYP_CD_5);
    	    			List<CstNpSocialRlDTO> listCstNpSocia = this.cstNpSocialRlService.searchList(cstNpSocQc);
	    				if(CollectionUtils.isNotEmpty(listCstNpSocia)){
	    					logger.info("=======配偶信息   ========="+listCstNpSocia.get(0).getId()+"=================");
	    					vc.put("mateCertNo", listCstNpSocia.get(0).getCertNo());
	    					vc.put("mateRlNm", listCstNpSocia.get(0).getRlNm());
	    					vc.put("mateMp", listCstNpSocia.get(0).getMp());
	    					vc.put("matePostAddr", listCstNpSocia.get(0).getPostAddr());
	    					vc.put("mateWorkAddr", listCstNpSocia.get(0).getWorkAddr());
	    					vc.put("mateWorkPlc", listCstNpSocia.get(0).getWorkPlc());
	    					if(StringUtils.isNotEmpty(listCstNpSocia.get(0).getRlNm())){
	    						vc.put("mateRlNm2","、"+ listCstNpSocia.get(0).getRlNm());
	    					}
	    				}
    				}
					VelocityUtil.createDoc(tmplFileNm, vc, request, response, tmplNm, Integer.valueOf(fileTypCd), expTmplPath);
				} catch (NumberFormatException e) {
					BaseLogUtils.error(logger, "extcon/sysExpTmpl.toCreateDoc", e.getMessage());
				} catch (IOException e) {
					BaseLogUtils.error(logger, "extcon/sysExpTmpl.toCreateDoc", e.getMessage());
				}
	    	}else{
	    		//直接输出原文件
	    		try {
					VelocityUtil.directOutDoc(tmplFileNm, response, tmplNm, Integer.valueOf(fileTypCd), expTmplPath);
				} catch (NumberFormatException e) {
					BaseLogUtils.error(logger, "extcon/sysExpTmpl.toCreateDoc", e.getMessage());
				} catch (FileNotFoundException e) {
					BaseLogUtils.error(logger, "extcon/sysExpTmpl.toCreateDoc", e.getMessage());
				}
	    	}
	    	
	    }
	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载SysExpTmpl列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("extcon/sysExpTmpl/sysExpTmplList");
		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载SysExpTmpl Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("extcon/sysExpTmpl/sysExpTmplModify");
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载SysExpTmpl Modify页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("extcon/sysExpTmpl/sysExpTmplModify");
		//this.prepare(request,mav);
		
		String id=request.getParameter("id");
		SysExpTmplVO sysExpTmplVO = this.sysExpTmplService.selectById(Long.valueOf(id));
        mav.addObject("sysExpTmplVO", sysExpTmplVO);
		return mav;
	}
	
	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	
    }

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeSysExpTmplByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeSysExpTmplByIds", "删除SysExpTmpl数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			boolean success = this.sysExpTmplService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeSysExpTmplByIds", "删除SysExpTmpl数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeSysExpTmplByIds", "删除SysExpTmpl数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeSysExpTmplByIds", "删除SysExpTmpl数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeSysExpTmplByIds", "删除SysExpTmpl数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getSysExpTmplById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getSysExpTmplById", "获取SysExpTmpl数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			SysExpTmplVO vo = this.sysExpTmplService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getSysExpTmplById", "获取SysExpTmpl数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getSysExpTmplById", "获取SysExpTmpl数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getSysExpTmplById", "获取SysExpTmpl数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getSysExpTmplById", "获取SysExpTmpl数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addSysExpTmpl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		SysExpTmplVO entity = null;//获取参数
		try {
			entity = this.getRequestParamForSysExpTmpl(request);//获取参数
			Long id = this.sysExpTmplService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "addSysExpTmpl", "新增SysExpTmpl数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addSysExpTmpl", "新增SysExpTmpl数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addSysExpTmpl", "新增SysExpTmpl数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifySysExpTmpl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		SysExpTmplVO entity = null;
		try {
			entity = this.getRequestParamForSysExpTmpl(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifySysExpTmpl", "修改SysExpTmpl信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.sysExpTmplService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifySysExpTmpl", "修改SysExpTmpl数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifySysExpTmpl", "修改SysExpTmpl数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifySysExpTmpl", "修改SysExpTmpl数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifySysExpTmpl", "修改SysExpTmpl数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return 
	 */
	private SysExpTmplVO getRequestParamForSysExpTmpl(HttpServletRequest request) throws BaseException{
		//获取参数
		String id = request.getParameter("id");//主键
		String grpCd = request.getParameter("grpCd");//模板组代码（SYS0025）
		String expTmplPath = request.getParameter("expTmplPath");//导出模板路径
		String tmplFileNm = request.getParameter("tmplFileNm");//模板文件名称
		String tmplNo = request.getParameter("tmplNo");//模板编号
		String tmplNm = request.getParameter("tmplNm");//模板名称
		String javaClzNm = request.getParameter("javaClzNm");//文件生成java类名
		String fileTypCd = request.getParameter("fileTypCd");//文件类型（SYS0026）
		String sortNo = request.getParameter("sortNo");//文件排序
		String buOrgCd = request.getParameter("buOrgCd");//所属事业部
		String sysCd = request.getParameter("sysCd");//系统代码（SYS0001）

		//验证参数并赋值
		SysExpTmplVO entity = new SysExpTmplVO();
 		//entity.setGrpCd(grpCd);//模板组代码（SYS0025）
 		//entity.setExpTmplPath(expTmplPath);//导出模板路径
 		//entity.setTmplFileNm(tmplFileNm);//模板文件名称
 		//entity.setTmplNo(tmplNo);//模板编号
 		//entity.setTmplNm(tmplNm);//模板名称
 		//entity.setJavaClzNm(javaClzNm);//文件生成java类名
 		//entity.setFileTypCd(fileTypCd);//文件类型（SYS0026）
 		//entity.setSortNo(sortNo);//文件排序
 		//entity.setBuOrgCd(buOrgCd);//所属事业部
 		//entity.setSysCd(sysCd);//系统代码（SYS0001）
	
//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
		}
		
		return entity;
	}
}

